﻿namespace AnQinFrameWorkAPI.Service.SystemCore;

/// <summary>
///     附件上传业务层
/// </summary>
public class UpLoadService
{
    /**
     * 附件上传
     */
    public async Task<string> FileUpload(IFormFile file)
    {
        //判断文件是否有效
        if (file == null) return null;
        var savepath = "G:\\picture";

        #region 保存路径，如果不存在则创建

        if (!Directory.Exists(savepath)) Directory.CreateDirectory(savepath);

        #endregion

        //文件信息
        var filename = Path.GetFileNameWithoutExtension(file.FileName);
        var extension = Path.GetExtension(file.FileName);


        //保留文件名
        var newName = filename;
        var i = 1;
        while (true)
            if (File.Exists(savepath + "\\" + newName + extension))
            {
                newName = filename + "（" + i + "）";
                i++;
            }
            else
            {
                filename = newName;
                break;
            }

        var imagepath = string.Format("{0}\\{1}{2}", savepath, filename, extension);
        using (var stream = file.OpenReadStream())
        {
            using (var fs = new FileStream(imagepath, FileMode.CreateNew))
            {
                stream.CopyTo(fs);
            }
        }

        return string.Format("{0}{1}", filename, extension);
    }
}